﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

public class UDPClient : UDPRemote
{
    public int continueConnectFailedCount;

    bool m_ToPing;

    
    public UDPClient(long clientId, IPEndPoint ipEndPoint, UDPSocketServer uDPSocketServer) : base(clientId, ipEndPoint, uDPSocketServer)
    {
        StartPing();
    }

    void StartPing()
    {
        m_ToPing = true;

        var ping = new Thread(PingThread);
        ping.Start();
    }

    //TODO.改在Update中
    protected void PingThread()
    {
        while (m_ToPing )
        {
            Thread.Sleep(10000);

            Ping();

            if(m_SocketServer == null || this.m_EndPoint == null)
            {
                break;
            }
        }
    }
    public void Disconnect()
    {
        GameDebug.LogShowy($"{this.userID}  clientID:{this.clientId} userId:{this.userID} disconnect");
        m_ToPing = false;

        this.Release();
    }

    //public void Reconnect()
    //{
    //    GameDebug.LogShowy($"{this.userID}  clientID:{this.clientId} userId:{this.userID} Reconnect");

    //    StartPing();
    //}
    public void Ping()
    {
        GameDebug.Log($"UDPClient  {this.clientId} userId:{this.userID}  发送Ping :{ipEndPoint}");

        //TODO.改为SendPacket
        if (m_SocketServer != null && ipEndPoint != null)
        {
            m_SocketServer._SendData(new byte[] { ClientsManagerBase.PingByte }, this.ipEndPoint);
        }
        else
        {
            GameDebug.LogError("m_SocketServer == null");
        }
    }

    public override void OnReceiveData(byte[] data)
    {
        if (data.Length == 1)
        {
            this.OnReceivePingResponse(data);
        }
        else
        {
            GameDebug.Log($"client:{clientId}  userId:{userID}  处理数据");

            this.OnProcessMessageData(data);
        }
    }

    public void OnReceivePingResponse(byte[] data)
    {
        if(data.Length == 1 && data[0] == ClientsManagerBase.PingByte)
        {
            GameDebug.Log($"client:{clientId}  userId:{userID}  ping 返回");
        }
        else
        {
            GameDebug.LogError($"OnReceivePingResponse data:{data.GetArrStr()}");
        }
    }

}
    

